/**
 * The MIT License (MIT)
 *
 * Copyright (c) 2013-2018 Winlin
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

#include "..\src\srs\srs_librtmp.h"
#include "myThread.h"


void function(int thread_count)
{
	char rtmp_url[256] = { 0 };
	sprintf_s(rtmp_url, "rtmp://192.168.2.77:1935/live/livestream%d", thread_count);

	srs_rtmp_t rtmp = srs_rtmp_create(rtmp_url);

	if (srs_rtmp_handshake(rtmp) != 0) {
		srs_human_trace("simple handshake failed.");
		goto rtmp_destroy;
	}
	srs_human_trace("simple handshake success");

	if (srs_rtmp_connect_app(rtmp) != 0) {
		srs_human_trace("connect vhost/app failed.");
		goto rtmp_destroy;
	}
	srs_human_trace("connect vhost/app success");

	if (srs_rtmp_publish_stream(rtmp) != 0) {
		srs_human_trace("publish stream failed.");
		goto rtmp_destroy;
	}
	srs_human_trace("publish stream success");

	{
		uint8_t var = 0;
		uint32_t timestamp = 0;

		int dts = 0;
		int pts = 0;
		// @remark, to decode the file.
		int count = 0;

		//for (; p < h264_raw + file_size; ++var) {
		for (; ; ++var) {
			if (count++ == 9) {
				usleep(1000 * 1000 * count / 25);
				count = 0;
			}

			if (srs_rtmp_write_metadata_packet(rtmp) != 0) {
				goto rtmp_destroy;
			}
			srs_human_trace("sent packet: type=metadata, time=xxxx, size=xxxx");
		}
	}
rtmp_destroy:
	srs_rtmp_destroy(rtmp);
}

myThread* g_thread[50] = { 0 };

int main(int argc, char** argv)
{
	WSADATA WSAData;
	if (WSAStartup(MAKEWORD(1, 1), &WSAData)) {
		printf("WSAStartup failed.\n");
		return -1;
	}
	for (size_t i = 0; i < 50; i++)
	{
		g_thread[i] = new myThread();
		g_thread[i]->Start(function, i);
	}
	getchar();
rtmp_destroy:
    
	// cleanup socket for windows.
	WSACleanup();
    return 0;
}
